package com.suyx.job.controller;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.suyx.job.config.RedisUtils;
import com.suyx.job.entity.Page;
import com.suyx.job.entity.Result;
import com.suyx.job.entity.TaskInfo;
import com.suyx.job.service.ITaskInfoService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/31 0031 10:10
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/task")
public class TaskController  {

    private ITaskInfoService taskService;

    @Autowired
    public TaskController(ITaskInfoService taskService) {
        this.taskService = taskService;
    }
    
    @Autowired
	private RedisUtils redisService;
    /**
     * 查询梦幻任务信息
     */
    @GetMapping(value="/findTaskPage")
    public Page findTaskPage(TaskInfo taskInfo, Integer page, Integer limit)
    {
        return taskService.findTaskPage(taskInfo,page-1,limit);
    }

    /**
     * 保存梦幻任务信息
     */
    @PostMapping("/saveTask")
    public Result saveTask(TaskInfo taskInfo){
        try {
        	taskService.saveAndFlush(taskInfo);
            return new Result(true,"保存成功!");
        }catch (Exception e){
            log.error("保存梦幻任务信息数据报错："+ExceptionUtils.getStackTrace(e));
            return new Result(false,"保存失败："+e.getMessage());
        }
    }

    /**
     * 删除梦幻任务信息
     */
    @PostMapping("deleteTask")
    public Result deleteTask(Integer taskId){
        try {
        	taskService.deleteById(taskId);
            return new Result(true,"删除成功!");
        }catch (Exception e){
            log.error("删除梦幻任务信息数据报错：" + ExceptionUtils.getStackTrace(e));
            return new Result(false,"删除失败："+e.getMessage());
        }
    }

    @PostMapping(value = "/updateStatus")
    public Result updateStatus(Integer taskId, String status) {
        try {
        	TaskInfo taskInfo = taskService.getOne(taskId);
            if (taskInfo == null) {
                return new Result(false, "该id值不存在！操作失败");
            }
            taskInfo.setStatus(status);
            taskService.saveAndFlush(taskInfo);            
            return new Result(true, "操作成功！");
        } catch (Exception e) {
            log.error("出现异常！" + ExceptionUtils.getStackTrace(e));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//捕获异常后进行回滚
            return new Result(false, "出现异常！" + e.getMessage());
        }
    }


}
